from rest_framework import serializers
from .models import Product, UserProfile, ProductImage, Cart, CartItem, Order, OrderItem
from django.contrib.auth.models import User

# 用户信息序列化器 (在 authentication/views.py 中需要用到)
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'email']

# 用户扩展信息序列化器
class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ['contact_info', 'bio', 'phone', 'avatar']

# 商品图片序列化器
class ProductImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductImage
        fields = ['image']

# 商品序列化器
class ProductSerializer(serializers.ModelSerializer):
    seller = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())
    images = ProductImageSerializer(many=True, read_only=True)
    title = serializers.CharField(source='name', required=False)  # 将name映射为title
    publishTime = serializers.DateTimeField(source='created_at', read_only=True)  # 将created_at映射为publishTime

    class Meta:
        model = Product
        fields = ['id', 'title', 'price', 'original_price', 'category', 'condition', 'description', 'status', 'location', 'seller', 'publishTime', 'images']
    
    def create(self, validated_data):
        # 处理title字段映射到name字段
        if 'name' not in validated_data and 'title' in validated_data:
            validated_data['name'] = validated_data.pop('title')
        return super().create(validated_data)


# 购物车商品项序列化器
class CartItemSerializer(serializers.ModelSerializer):
    product_name = serializers.ReadOnlyField(source='product.name')
    product_price = serializers.ReadOnlyField(source='product.price')
    product_image = serializers.ReadOnlyField(source='product.images.first.image.url') # 获取第一张图的URL

    class Meta:
        model = CartItem
        fields = ['id', 'product', 'product_name', 'product_price', 'product_image', 'quantity']
        read_only_fields = ['product_name', 'product_price', 'product_image']


# 购物车序列化器
class CartSerializer(serializers.ModelSerializer):
    items = serializers.SerializerMethodField()

    class Meta:
        model = Cart
        fields = ['id', 'user', 'items', 'created_at']
        read_only_fields = ['user', 'created_at']

    def get_items(self, obj):
        # 只返回状态为'在售'的商品
        cart_items = obj.items.filter(product__status='在售')
        return CartItemSerializer(cart_items, many=True).data


# 订单商品项序列化器
class OrderItemSerializer(serializers.ModelSerializer):
    product_name = serializers.ReadOnlyField(source='product.name')
    # 添加商品图片信息
    product = serializers.SerializerMethodField()

    class Meta:
        model = OrderItem
        fields = ['id', 'product', 'product_name', 'quantity', 'price']
        read_only_fields = ['price']
        
    def get_product(self, obj):
        # 返回商品的完整信息，包括图片
        product = obj.product
        return {
            'id': product.id,
            'name': product.name,
            'images': [img.image.url for img in product.images.all()] if hasattr(product, 'images') else []
        }


# 订单序列化器
class OrderSerializer(serializers.ModelSerializer):
    items = OrderItemSerializer(many=True, read_only=True)

    class Meta:
        model = Order
        fields = ['id', 'user', 'total_price', 'status', 'created_at', 'updated_at', 'shipping_address', 'items']
        read_only_fields = ['user', 'total_price', 'created_at', 'updated_at']